// src/router/index.js
import Vue from "vue";
import VueRouter from "vue-router";

import Layout from "@/layout";
import Login from "@/views/Login.vue";
import Home from "@/views/Home.vue";
import NotFoundPage from "@/views/NotFoundPage.vue";
import OrderManagement from "@/views/OrderManagement.vue";
import UserManagement from "@/views/UserManagement.vue";
import DataStatistics from "@/views/DataStatistics.vue";

Vue.use(VueRouter);

const routes = [
  { path: "/login", component: Login },
  {
    path: "/",
    component: Layout,
    redirect: "/home",
    children: [
      { path: "/home", component: Home },
      { path: "/order", component: OrderManagement },
      { path: "/user", component: UserManagement },
      { path: "/statistics", component: DataStatistics },
    ],
  },
  {
    path: "*",
    component: NotFoundPage,
  },
];

const router = new VueRouter({
  routes,
});

router.beforeEach((to, from, next) => {
  // next();
  // 获取本地存储中的数据
  var token = localStorage.getItem("token");
  // 判断如果存在token表示已经登录放行，如果存在token并跳转到登录页面应该重定向到主页
  if (to.path !== "/login") {
    if (!token) {
      next("/login");
    } else {
      next();
    }
  } else {
    next();
  }
});

export default router;
